package com.argrace.smart.rokid;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.RuoQi_ActionEntity;
import com.argrace.smart.model.LocalDb_QingJingTable;
import com.argrace.smart.model.LocalDb_RuoQiDeviceTable;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/2/25.
 */

public class TcpListenerThread extends Thread {
    private String local_add;
    private int local_port;
    String str = "\"";

    public TcpListenerThread(String add, int port) {
        this.local_add = add;
        this.local_port = port;
    }


    //更改监听标志位
    private boolean isListen = true;   //线程监听标志位
    public ArrayList<ServerSocketThread> SST = new ArrayList<ServerSocketThread>();

    public void setIsListen(boolean b) {
        isListen = b;
    }

    public void closeSelf() {
        isListen = false;
        for (ServerSocketThread s : SST) {
            s.isRun = false;
        }
        SST.clear();
    }

    @Override
    public void run() {
        try {
            //开始监听后就启动
            String ip = "239.255.255.250";
            int port = 1900;
            KeePaLiveThread t = new KeePaLiveThread(ip, port, local_add, local_port);
            t.start();
            ServerSocket serverSocket = new ServerSocket(ConstantConfigure.ROKID_TCPLISTENER_PORT);
            while (isListen) {
                Socket socket = getSocket(serverSocket);
                if (socket != null) {
                    new ServerSocketThread(socket);
                }
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Socket getSocket(ServerSocket serverSocket) {
        try {
            return serverSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    class ServerSocketThread extends Thread {
        Socket socket = null;
        private PrintWriter pw;
        private InputStream is = null;
        private OutputStream os = null;
        private boolean isRun = true;

        ServerSocketThread(Socket socket) {
            this.socket = socket;
            try {
                os = socket.getOutputStream();
                is = socket.getInputStream();
                pw = new PrintWriter(os, true);
                start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void send(String msg) {
            pw.println(msg);
            pw.flush(); //强制送出数据
            try {
//                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            Log.i("info", "有新客户接入");
            byte buff[] = new byte[4096];
            String rcvMsg;
            int rcvLen;
            SST.add(this);
            try {
                while (isRun && !socket.isClosed() && !socket.isInputShutdown() && (rcvLen = is.read(buff)) != -1) {
                    rcvMsg = new String(buff, 0, rcvLen);
                    String id = null;
                    String method = null;
                    if (rcvMsg != null) {
                        Log.i("info", "客户端传来的数据是" + rcvMsg);
                        JSONObject obj = null;
                        try {
                            obj = new JSONObject(rcvMsg);
                            id = obj.getString("id");
                            method = obj.getString("method");

                            if (method != null && id != null && method.equals("list")) {

                                List<LocalDb_RuoQiDeviceTable> lists = DataSupport.findAll(LocalDb_RuoQiDeviceTable.class);
                                StringBuffer device_json_sb = new StringBuffer();
                                if (lists != null && lists.size() > 0) {
                                    for (int i = 0; i < lists.size(); i++) {
                                        //如果没添加过，则传输给rokid
                                        if (!lists.get(i).isIs_add()) {
                                            device_json_sb.append(lists.get(i).getDevice_json()).append(",");
                                        }
                                    }
                                }
                                device_json_sb.deleteCharAt(device_json_sb.length() - 1);
                                LocalDb_RuoQiDeviceTable entity = new LocalDb_RuoQiDeviceTable();
                                entity.setIs_add(true);
                                entity.updateAll("is_add = ? ", "false");
                                StringBuffer device_list_sb = new StringBuffer();
                                device_list_sb.append("{").append(str).append("jsonrpc").append(str).append(":").append(str).append("2.0").append(str).append(", ").append(str).append("result").append(str)
                                        .append(":[").append(device_json_sb.toString()).append("], ").append(str).append("id").append(str).append(": ").append(str).append(id).append(str).append("}");
                                Log.i("info", "拼接的字符串是" + device_list_sb.toString());
                                send(device_list_sb.toString());
                            }
                            if (method != null && id != null && method.equals("execute")) {
                                String deviceId = obj.getJSONObject("params").getJSONObject("device").getString("deviceId");
                                if (deviceId != null && !deviceId.equals("")) {

                                    RuoQi_ActionEntity action = com.alibaba.fastjson.JSONObject.parseObject(obj.getJSONObject("params").getString("action"), RuoQi_ActionEntity.class);
                                    if (action != null) {
                                        Log.i("info", "获得了此次action=" + action.toString());
                                        Log.i("info", "获得了此次deviceId=" + deviceId);
                                        String result = "{\"jsonrpc\": \"2.0\",\"result\":null,\"id\":";
                                        send(result + str + deviceId + str + "}");
                                        //根据type来区别场景和设备
                                        //场景的处理逻辑
                                        if (obj.getJSONObject("params").getJSONObject("device").getString("type").equals("scene")) {
                                            LocalDb_QingJingTable bean = DataSupport.find(LocalDb_QingJingTable.class, Integer.parseInt(deviceId.split(":")[1]));
                                            utils.executeQingJing(bean);
                                        }
                                        //设备的处理逻辑
                                        else {
                                            String action_str = action.getProperty();
                                            switch (action_str) {
                                                case "switch":
                                                    //0（关闭） 1（开启）
                                                    String switch_value = "0";
                                                    if (action.getName().equals("on")) {
                                                        switch_value = "1";
                                                    } else {
                                                        switch_value = "0";
                                                    }
                                                    if (deviceId.split("-").length > 1)//除两位和三位多控外，其他开关没有用：分割按键，开关都用swtich
                                                    {
                                                        sendMsg(deviceId.split("-")[1], switch_value, deviceId.split("-")[0]);
                                                    } else {
                                                        sendMsg("Swtich", switch_value, deviceId);
                                                    }
                                                    break;
                                                case "temperature":

                                                    if (deviceId.split("-").length > 1)//控制温度的只有地暖和空调，空调uuid后面有加-1等数字，用此来区分空调和非空调设备
                                                    {
                                                        setTemperatureUpAndDownAction(action.getName(), action.getValue(), deviceId.split("-")[0], deviceId.split("-")[1]);
                                                    } else {
                                                        setTemperatureUpAndDownAction(action.getName(), action.getValue(), deviceId);
                                                    }
                                                    break;
                                                case "fanspeed":
                                                    if (deviceId.split("-").length > 1)//控制风速的只有新风机和空调，空调uuid后面有加-1等数字，用此来区分空调和非空调设备
                                                    {
                                                        setWindSpeedUpAndDownAction(action.getName(), action.getValue(), deviceId.split("-")[0], deviceId.split("-")[1]);
                                                    } else {
                                                        setWindSpeedUpAndDownAction(action.getName(), action.getValue(), deviceId);
                                                    }

                                                    break;
                                                //位置量暂时不支持
                                                case "position":
                                                    break;
                                                case "mode":
                                                    //必须知道是第几路空调才进行设置
                                                    if (deviceId.split("-").length > 1) {
                                                        setDeviceModel(action.getName(), action.getValue(), deviceId.split("-")[0], deviceId.split("-")[1]);
                                                    }

                                                    break;
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
                SST.clear();
                Log.i("info", "run: 断开连接");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDeviceModel(final String action_name, final String action_value, final String uuid, final String position) {
        String key = "WorkMode" + "_" + position;
        switch (action_name) {
            case "cool":
                sendMsg(key, "1", uuid);
                break;
            case "heat":
                sendMsg(key, "2", uuid);
                break;
            case "fan":
                sendMsg(key, "3", uuid);
                break;
            case "dry":
                sendMsg(key, "4", uuid);
                break;
        }

    }

    //    position代表第几路空调
    private void setWindSpeedUpAndDownAction(final String action_name, final String action_value, final String uuid, final String position) {
        //查询设备最新状态
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        JSONObject result = null;
        final String key = "WindSpeed" + "_" + position;
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                Key_ValueEntity bean_fengsu = JSON.parseObject(obj.getString(key), Key_ValueEntity.class);
                long fengsu_long = Long.parseLong(bean_fengsu.getValue());
                switch (action_name) {
                    case "up":
                        fengsu_long++;
                        break;
                    case "down":
                        fengsu_long--;
                        break;
                    case "max":
                        fengsu_long = 4;
                        break;
                    case "min":
                        fengsu_long = 2;
                    case "num":
                        fengsu_long = Long.parseLong(action_value) + 1;
                        break;
                }
                if (fengsu_long > 4) {
                    fengsu_long = 4;
                }
                if (fengsu_long < 2) {
                    fengsu_long = 2;
                }
                sendMsg(key, String.valueOf(fengsu_long), uuid);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void setWindSpeedUpAndDownAction(final String action_name, final String action_value, final String uuid) {
        //查询设备最新状态
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        JSONObject result = null;
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                Key_ValueEntity bean_fengsu = JSON.parseObject(obj.getString("WindSpeed"), Key_ValueEntity.class);
                long fengsu_long = Long.parseLong(bean_fengsu.getValue());
                switch (action_name) {
                    case "up":
                        fengsu_long++;
                        break;
                    case "down":
                        fengsu_long--;
                        break;
                    case "max":
                        fengsu_long = 4;
                        break;
                    case "min":
                        fengsu_long = 2;
                    case "num":
                        fengsu_long = Long.parseLong(action_value) + 1;
                        break;
                }
                if (fengsu_long > 4) {
                    fengsu_long = 4;
                }
                if (fengsu_long < 2) {
                    fengsu_long = 2;
                }
                sendMsg("WindSpeed", String.valueOf(fengsu_long), uuid);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void setTemperatureUpAndDownAction(final String action_name, final String action_value, final String uuid) {
        //查询设备最新状态
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        JSONObject result = null;
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                Key_ValueEntity bean_shedingwendu = JSON.parseObject(obj.getString("TargetTemperature"), Key_ValueEntity.class);
                long shedingwendu_long = Long.parseLong(bean_shedingwendu.getValue());
                switch (action_name) {
                    case "up":
                        shedingwendu_long++;
                        break;
                    case "down":
                        shedingwendu_long--;
                        break;
                    case "max":
                        shedingwendu_long = 32;
                        break;
                    case "min":
                        shedingwendu_long = 16;
                    case "num":
                        shedingwendu_long = Long.parseLong(action_value);
                        break;
                }
                if (shedingwendu_long > 32) {
                    shedingwendu_long = 32;
                }
                if (shedingwendu_long < 16) {
                    shedingwendu_long = 16;
                }
                sendMsg("TargetTemperature", String.valueOf(shedingwendu_long), uuid);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    //    position代表第几路空调
    private void setTemperatureUpAndDownAction(final String action_name, final String action_value, final String uuid, final String position) {
        //查询设备最新状态
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        JSONObject result = null;
        final String key = "TargetTemperature" + "_" + position;
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                Key_ValueEntity bean_shedingwendu = JSON.parseObject(obj.getString(key), Key_ValueEntity.class);
                long shedingwendu_long = Long.parseLong(bean_shedingwendu.getValue());
                switch (action_name) {
                    case "up":
                        shedingwendu_long++;
                        break;
                    case "down":
                        shedingwendu_long--;
                        break;
                    case "max":
                        shedingwendu_long = 32;
                        break;
                    case "min":
                        shedingwendu_long = 16;
                    case "num":
                        shedingwendu_long = Long.parseLong(action_value);
                        break;
                }
                if (shedingwendu_long > 32) {
                    shedingwendu_long = 32;
                }
                if (shedingwendu_long < 16) {
                    shedingwendu_long = 16;
                }
                sendMsg("key", String.valueOf(shedingwendu_long), uuid);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void sendMsg(String key, String value, String uuid) {
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("setParams", "{\"" + key + "\":\"" + value + "\"}");
        Log.i("info", "收到语音后发送的数据是" + "{\"" + key + "\":\"" + value + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "发送消息成功" + transitoryResponse.data);
//                getDeviceDetailInfo();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "发送消息失败");
            }
        });
    }
}
